package com.springboot.experiment2;

        import org.slf4j.Logger;
        import org.slf4j.LoggerFactory;
        import org.springframework.boot.CommandLineRunner;
        import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
        import org.springframework.boot.context.properties.EnableConfigurationProperties;
        import org.springframework.context.ApplicationContext;
        import org.springframework.context.ApplicationListener;
        import org.springframework.context.annotation.Bean;
        import org.springframework.context.event.ApplicationEventMulticaster;
        import org.springframework.context.event.SimpleApplicationEventMulticaster;
        import org.springframework.context.support.AbstractApplicationContext;
        import org.springframework.core.env.Environment;
        import org.springframework.scheduling.annotation.AsyncAnnotationBeanPostProcessor;
        import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
        import org.springframework.stereotype.Component;

        import java.util.Arrays;
        import java.util.concurrent.ThreadPoolExecutor;

/**
 * author 陈伯瑞
 * date 2020/4/9 0009 14:01
 * version 1.0
 **/
@EnableConfigurationProperties(CustomProperties.class)
public class AutoConfig {
    @Bean
    @ConditionalOnProperty(prefix = "jon.auto",name="enable",havingValue = "true")
    CommandLineRunner createCustomerLineRunner(Environment env){
        return  new CustomerCommandLineRunner(env);
    }

    @Bean
    public CommandLineRunner commandLineRunner(ApplicationContext ctx) {
        return args -> {
            System.out.println("由springboot注册生成的所有bean：");
            String[] beanNames = ctx.getBeanDefinitionNames();
            Arrays.sort(beanNames);
            for (String beanName : beanNames) {
                System.out.println(beanName);
            }
        };
    }
    /**
     * 自定义一个事件发布器
     * */
    @Bean(AbstractApplicationContext.APPLICATION_EVENT_MULTICASTER_BEAN_NAME)
    ApplicationEventMulticaster customApplicationEventMulticaster(ThreadPoolTaskExecutor taskExecutor){

        SimpleApplicationEventMulticaster eventMulticaster=new SimpleApplicationEventMulticaster();
        eventMulticaster.setTaskExecutor(taskExecutor);
        return  eventMulticaster;
    }

    /**
     * 自定义线程池
     */
    @Bean("taskExecutor")
    public ThreadPoolTaskExecutor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(20);
        executor.setMaxPoolSize(20);
        executor.setQueueCapacity(200);
        executor.setKeepAliveSeconds(200);
        /**
         * 线程池前缀
         */
        executor.setThreadNamePrefix("MyExecutor");
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.setWaitForTasksToCompleteOnShutdown(true);
        executor.setAwaitTerminationSeconds(200);
        return executor;
    }
}
